﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using WidgetsDesign.API.Dtos;
using WidgetsDesign.API.Models;
using WidgetsDesign.API.Services;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WidgetsDesign.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly IEmployeeRepository _employeeRepository;
        private readonly IMapper _Mapper;
        public EmployeeController(IEmployeeRepository employeeRepository, IMapper mapper)
        {
            _employeeRepository = employeeRepository;
            _Mapper = mapper;
        }
        // GET: api/<EmployeeController>
        [HttpGet]
        public async Task<IActionResult> GetEmployeeList([FromQuery] int pageIndex, int pageSize)
        {
            var result = await _employeeRepository.GetEmployeesList(pageIndex, pageSize);
            var total = _employeeRepository.GetEmployeesListTotal();
            return Ok(new { ret = true, code = 200, data = result, total });
        }
        [HttpPost]
        public async Task<IActionResult> AddEmployee([FromBody] EmployeeDto employeeDto)
        {
            if (String.IsNullOrEmpty(employeeDto.EmployeeId))
            {
                employeeDto.EmployeeId = Guid.NewGuid().ToString();
                var employeeModel = _Mapper.Map<EmployeeModel>(employeeDto);
                _employeeRepository.AddEmployees(employeeModel);
                await _employeeRepository.SaveAsync();
                return Ok(new { ret = true, code = 200, data = employeeModel, message = "添加成功！" });
            }
            else
            {
                var employeeModel = _Mapper.Map<EmployeeModel>(employeeDto);
                _employeeRepository.UpdateEmployees(employeeModel);
                await _employeeRepository.SaveAsync();
                return Ok(new { ret = true, code = 200, data = employeeModel, message = "更新成功！" });

            }
        }
        [HttpGet]
        public async Task<IActionResult> DeleteEmployee([FromQuery] string id)
        {
            _employeeRepository.DeleteEmployees(id);
            var res = await _employeeRepository.SaveAsync();
            return Ok(new { ret = res, code = 200, data = new { }, message = res ? "删除成功！" : "未找到该员工或该员工已经被删除" });
        }
        [HttpGet]
        public async Task<IActionResult> GetEmployee([FromQuery] string id)
        {
            var info = await _employeeRepository.GetEmployees(id);
            return Ok(new { ret = true, code = 200, data = info });
        }
    }
}
